/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.swagger.config;

import java.util.Optional;
import org.elsfs.cloud.common.swagger.annotation.EnableSwaggerDoc;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * openapi 配置类
 *
 * @author zeng
 */
public class OpenAPIDefinitionImportSelector implements ImportBeanDefinitionRegistrar {

  /**
   * 注册Bean定义方法
   *
   * @param metadata 注解元数据
   * @param registry Bean定义注册器
   */
  @Override
  public void registerBeanDefinitions(
      AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
    Optional.ofNullable(metadata.getAnnotationAttributes(EnableSwaggerDoc.class.getName(), true))
        .map(attrs -> attrs.get("value"))
        .ifPresent(
            value -> {
              createBeanDefinition(
                  registry, "openAPIMetadataRegister", OpenAPIMetadataRegister.class, value);
              createBeanDefinition(registry, "openAPIDefinition", OpenAPIDefinition.class, value);
            });
  }

  /**
   * 创建Bean定义
   *
   * @param registry Bean定义注册器
   * @param beanName Bean名称
   * @param beanClass Bean类
   * @param value Bean属性值
   */
  private void createBeanDefinition(
      BeanDefinitionRegistry registry, String beanName, Class<?> beanClass, Object value) {
    BeanDefinitionBuilder beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(beanClass);
    beanDefinition.addPropertyValue("path", value);
    registry.registerBeanDefinition(beanName, beanDefinition.getBeanDefinition());
  }
}
